package top.greatxiaozou.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import top.greatxiaozou.model.Result;


import java.util.Date;
import java.util.List;

/*
* 用于生成token的工具类
* */
public class TokenUtils {
    static JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("wdnmdzys")).build();
    static String singnature = "wdnmdzys";
    public static String getToken(String username,String password){
       return JWT.create()
                .withExpiresAt(new Date(System.currentTimeMillis()+1200000))  //设置过期时间
                .withAudience(username,password)//设置接受方信息，一般时登录用户
                .sign(Algorithm.HMAC256(singnature)); //使用HMAC算法，111111作为密钥加密

    }

    public static List getInfoFromToken(String token){
        DecodedJWT jwt = jwtVerifier.verify(token);
        return jwt.getAudience();
    }

    public static boolean isActive(String token){
        DecodedJWT jwt = jwtVerifier.verify(token);
        Date expiresAt = jwt.getExpiresAt();

        if (expiresAt.compareTo(new Date())==-1){
            return false;
        }
        return true;
    }

    /*
    * @return:
    *   1：token有效
    *   2：token过期
    *   3：token为空
    * */

    public static ResponseEntity<Result> isEffective(String token){
        try {
            isActive(token);
        }catch (TokenExpiredException e){
            return ResultsUtils.faild("token过期，请重新登录", HttpStatus.FORBIDDEN);
        }
        if (token==null){
            return ResultsUtils.faild("未登录,无令牌",HttpStatus.FORBIDDEN);
        }
        return null;

    }
}
